# -*- coding: utf-8 -*-
#
# Author:: JonnyHan
# Date:: 2020/8/19

import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from submodules.common.lib.local_paths import chrome_driver_path
from lib.curl_ import curl_to_dict
from lib.json_ import trans_jsonFile_to_dict, trans_dict_to_jsonFile


def get_jwtToken_to_file_by_cookies():
    # 通过curl数据获取cookies
    # 获取原始curl数据
    curl_sso_dict = trans_jsonFile_to_dict("config_private/curl_sso.json")
    sso_curl_charles = curl_sso_dict["curl_charles"]
    # 格式化curl为dict
    curl_dict = curl_to_dict(sso_curl_charles)
    # 设置无头模式运行
    chrome_options = Options()
    chrome_options.add_argument('--headless')
    driver = webdriver.Chrome(chrome_driver_path, options=chrome_options)
    driver.implicitly_wait(10)
    driver.maximize_window()

    # 启动并设置cookies
    driver.get("https://sso.bytedance.com/")
    for k, v in curl_dict['cookies'].items():
        driver.add_cookie({'name': k, 'value': v})

    # 获取token并写入配置文件
    driver.get("https://cloud.bytedance.net/rds/detail/db/cn/f_b/autoSQL")
    # 中间有跳转错误页重定向过程 等待数秒继续 错误提示：no token present in request 原因未知
    time.sleep(3)
    driver.find_element_by_xpath('//*[@id="content__slot"]/div[2]/div/div/div/div[2]/ul/li[6]/span').click()
    # 处理jwtToken不存在
    token = driver.execute_script('return window.localStorage.getItem("jwtToken");')
    if token != None:
        token = token.strip('"')
        dict_token = {"token": token}
        trans_dict_to_jsonFile(dict_token, "config_private/dbs_token.json")
        logger.info(token)
    else:
        logger.info(token)
        logger.info("jwtToken为空或不存在，可能是sso cookies已过期，可尝试更新配置文件后重试")
    driver.close()


